package com.xutianpeng.disk.role.service.impl;

import com.xutianpeng.disk.menu.exception.MenuOccupyException;
import com.xutianpeng.disk.mybatis.entity.PtRoleEntity;
import com.xutianpeng.disk.mybatis.entity.PtUserEntity;
import com.xutianpeng.disk.mybatis.flexigrid.PagingEntity;
import com.xutianpeng.disk.mybatis.flexigrid.TblResponseEntity;
import com.xutianpeng.disk.mybatis.ztree.ZtreeEntity;
import com.xutianpeng.disk.role.entity.SearchRoleEntity;
import com.xutianpeng.disk.role.repository.RoleDao;
import com.xutianpeng.disk.role.service.RoleService;
import com.xutianpeng.disk.user.exeption.UserOccupyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleDao roleDao;

    @Override
    public TblResponseEntity<PtRoleEntity> queryRoleInfoListByPage(SearchRoleEntity entity, PagingEntity paging) {
        TblResponseEntity<PtRoleEntity> response = new TblResponseEntity<>();
        Integer total = roleDao.queryRoleListTotal(entity);
        response.setTotal(total);

        paging.deal(PtRoleEntity.class, total);
        response.setPage(paging.getPage());

        List<PtRoleEntity> list = roleDao.queryRoleInfoListByPage(entity, paging);
        response.setRawRecords(list);
        response.deal();

        return response;
    }

    @Override
    public PtRoleEntity queryRoleInfoById(String roleUuid) {
        return roleDao.queryRoleInfoById(roleUuid);
    }

    @Override
    public void modifyRoleInfoById(PtRoleEntity entity) {
        roleDao.modifyRoleInfoById(entity);
    }

    @Override
    public void addRoleInfoById(PtRoleEntity entity) {
        roleDao.addRoleInfoById(entity);
    }

    @Override
    public void deleteRoleByIds(String ids) throws UserOccupyException, MenuOccupyException {
        String[] roleArray = ids.split(",");
        StringBuffer userSb = new StringBuffer();
        StringBuffer menuSb = new StringBuffer();

        for (String roleUuid : roleArray) {
            // 检查角色是否关联用户
            String userName = roleDao.queryUserListByRole(roleUuid);
            if (userName != null) {
                userSb.append(userName).append(",");
            }

            // 检查角色是否关联菜单
            String menuName = roleDao.queryMenuListByRole(roleUuid);
            if (menuName != null) {
                menuSb.append(menuName).append(",");
            }
        }

        // 处理用户关联冲突
        if (userSb.length() > 0) {
            throw new UserOccupyException(userSb.substring(0, userSb.length() - 1));
        }

        // 处理菜单关联冲突
        if (menuSb.length() > 0) {
            throw new MenuOccupyException(menuSb.substring(0, menuSb.length() - 1));
        }

        // 执行删除
        roleDao.deleteRoleByIds(roleArray);
    }

    @Override
    public List<ZtreeEntity> queryMenuTreeListByRole(String roleUuid) {
        List<ZtreeEntity> menuList = roleDao.queryMenuTreeList();
        List<String> roleMenuIds = roleDao.queryMenuByRole(roleUuid);

        // 标记已选中的菜单
        for (ZtreeEntity menu : menuList) {
            if (roleMenuIds.contains(menu.getId())) {
                menu.setChecked(true);
            }
        }
        return menuList;
    }

    @Override
    public void saveRoleRefMenu(String roleUuidArray, String menuIdArray) {
        String[] roleUuids = roleUuidArray.split(",");
        String[] menuIds = menuIdArray.split(",");

        for (String roleUuid : roleUuids) {
            // 先删除旧关联
            roleDao.deleteMenuByRole(roleUuid);
            // 再插入新关联
            for (String menuId : menuIds) {
                roleDao.insertMenuRefRole(roleUuid, menuId);
            }
        }
    }

    @Override
    public TblResponseEntity<PtUserEntity> queryUsersByRoleUuid(String roleUuid, PagingEntity paging) {
        TblResponseEntity<PtUserEntity> response = new TblResponseEntity<>();

        // 查询总数量
        Integer total = roleDao.queryUserCountByRole(roleUuid);
        response.setTotal(total);

        // 处理分页
        paging.deal(PtUserEntity.class, total);
        response.setPage(paging.getPage());

        // 查询用户列表
        List<PtUserEntity> userList = roleDao.queryUsersByRoleUuid(roleUuid, paging);
        response.setRawRecords(userList);
        response.deal();

        return response;
    }

    /**
     * 新增：保存用户与角色的关联关系（先删旧关联，再插新关联）
     * 解决"一个用户被多角色错误关联"的核心方法
     */
    public void saveUserRefRole(String userUuid, String roleUuidArray) {
        String[] roleUuids = roleUuidArray.split(",");

        // 1. 先删除用户的所有旧角色关联（关键！避免关联叠加）
        roleDao.deleteRoleByUser(userUuid);

        // 2. 插入新的角色关联
        for (String roleUuid : roleUuids) {
            roleDao.insertUserRefRole(userUuid, roleUuid);
        }
    }
}
